/**
 * Created by moko1988 on 15/12/1.
 */
define([
    'backbone',
    'models/recharge/chCharge',
    'text!templets/recharge/chCharge.html',
    'utils/dataTableUtil',
    'utils/datePickerUtil',  //时间框
    'utils/urlUtil',  
    'jquerypage',
    'select2',
    'moment'
], function(
    BackBone,
    Model,
    Tpl,
    DataTable,
    DatePicker,  //时间框
    UrlUtil
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun', //添加资源
            'click [role=edit]': 'editFun', //修改资源
            'click [role=del]': 'delFun', //删除资源
            'change #pageSize': 'changePageSize', //选择分页宽度
            'click [role=rank]': 'rank', //排序
            'click [role=review]': 'review', //审核
            'click [role=recommend]': 'recommend', //推荐
            'click #checkAll': 'checkAll', //全选、取消
            'click input[name=idarr]': 'checkItem', //选择、取消单条记录
            'change #ad_category': 'changeListCategory_ad',
            'change #game_category': 'changeListCategory_game',
            'change #datePicker': 'changeListCategory_time',
             'click [role=search]': 'searchCharge'//查询
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';

            // **************日期框的初始化*******************
            this.start_time = moment().format('YYYY-MM-DD ');
            this.end_time = moment().format('YYYY-MM-DD ');
            this.start = (new Date(this.start_time).getTime())/1000;
            this.end = (new Date(this.end_time).getTime())/1000;
            this.status = '1';

            var _this = this;
            DatePicker.start({
                'isSingle': false,
                'callback': function(start, end){
                    _this.changeTime(start, end);
                },
                'minDate': '2015-10-01',
                'startDate': this.start_time,
                'endDate': this.end_time
            });
            this.renderCategory();
            // *********************************

            this.idArr = [];
            this.categoryid = '';
            $('#pageSize').select2();
            this.renderCategory_ad();
            this.renderCategory_game();

         } ,
         params:{
            channel:"",
            game:"",
            start_time:"",
            end_time: ""

        },
        renderCategory: function(){
            // var opts = '<option>选择类别</option>';
            //     opts += '<option value="1">已结算</option>';
            //     opts += '<option value="0">未结算</option>';
            // $('#list-category').html(opts).prop('disabled',false).select2();
            // this.render();
        },
        
        // 日期下拉框的方法
        changeTime: function (start, end){
            var startDate = start.format('YYYY-MM-DD HH:mm:ss'),
                endDate = end.format('YYYY-MM-DD HH:mm:ss');
            $('#datePicker').find('span').html(startDate + '~' + endDate);
            this.start = (new Date(startDate).getTime())/1000;
            // var Start = this.start;
            this.end = (new Date(endDate).getTime())/1000;
            this.page = 1;
            this.changeListCategory_time();
        },

        renderCategory_ad: function(){
            var _this = this;
            Model.fetchCategory_ad({
                type: 'get',
                success: function(map) {
                    //console.log(map);
                    var opts = '<option value="">选择渠道</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.corporate_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#ad_category').html(opts).prop('disabled',false).select2();
                    // $('#game_category').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            })
        },

         renderCategory_game: function(){
            var _this = this;
            Model.fetchCategory_game({
                type: 'get',
                success: function(map) {
                    //console.log(map);
                    var opts = '<option value="">选择游戏</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.game_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    // $('#ad_category').html(opts).prop('disabled',false).select2();
                    $('#game_category').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            })
        },

        changeListCategory_ad: function(e){
            var $target = $(e.currentTarget);
            this.params["channel"] = $target.val();
        },
        changeListCategory_game: function(e){
            var $target = $(e.currentTarget);
            console.log($target);
            this.params["game"] = $target.val();
        },

        changeListCategory_time: function(e){         
             this.params["start_time"] = this.start;
             this.params["end_time"] = this.end;
        },

       searchCharge: function(e){
            var _this = this;
            Model.search({
                type: 'post',
                data: {
                    user_id:  _this.params["channel"],
                    game_id:  _this.params["game"],
                    start_time:  _this.params["start_time"],
                    end_time:  _this.params["end_time"],
                    page: this.page,
                    page_size: this.listRows
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if(_this.categoryid == ''){

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        }else{

                            if (_this.page == 1 && i == 0) {

                                rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            }
                            if (_this.page == _this.pageTotal && i == (count - 1)) {

                                rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                            }
                        }

                      o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';
                    
                        if(o.date_per_day!=''){o.date_per_day = moment(o.date_per_day * 1000).format('YYYY-MM-DD HH:mm')}else{o.date_per_day = ''};
                

                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '渠道名称', '游戏名称', '充值金额', '分层金额' , '扣量金额' , '日期'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'channel_name'),
                            _.pluck(data,'gname'),
                            _.pluck(data,'money_everyday'),
                            _.pluck(data,'layered_money'),
                            _.pluck(data,'reduce_money'),

                            _.pluck(data,'date_per_day')
                        );


                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });

                }
            })
        },

        /*排序*/
        rank: function(e) {
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },
        /*选择分页宽度*/
        changePageSize: function(e) {
            var $target = $(e.currentTarget),
                val = $target.val();
            this.listRows = val;
            this.render();
        },
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                type: 'post',
                data: {
                    ad_id:1,
                    page: this.page,
                    page_size: this.listRows,
                    //cid: this.categoryid
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if(_this.categoryid == ''){

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        }else{

                            if (_this.page == 1 && i == 0) {

                                rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                            }
                            if (_this.page == _this.pageTotal && i == (count - 1)) {

                                rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                            }
                        }

                       o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';
                    
                        if(o.date_per_day!=''){o.date_per_day = moment(o.date_per_day * 1000).format('YYYY-MM-DD HH:mm')}else{o.date_per_day = ''};
                

                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '渠道名称', '游戏名称', '充值金额', '分层金额' ,'扣量金额' , '日期'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'channel_name'),
                            _.pluck(data,'gname'),
                            _.pluck(data,'money_everyday'),
                            _.pluck(data,'layered_money'),
                            _.pluck(data,'reduce_money'),

                            _.pluck(data,'date_per_day')
                        );

                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });

                }
            })
        },
        /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.searchCharge();
        },
        // addFun: function() {
        //     window.location.hash = 'view/article-add'
        // },
        /*修改*/
        editFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.attr('data-id'),
                params = UrlUtil.parse2Str({
                    id: id
                }),
                url = 'view/article-edit/' + params;
            location.hash = url;
        },
        /*审核/取消审核*/
        review: function(e){
            // console.log(e);

            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                _this = this;

             ad_id = '';
             money = '';
                for(var i=0;i<this.idArr.length;i++){
                    if (this.idArr.length) {
                        money+=$('#money'+this.idArr[i]).html();
                        ad_id+=$('#ad_id'+this.idArr[i]).html();
                        money+=',';
                        ad_id+=',';

                }
                }
            ad_id = ad_id.substr(0,ad_id.length-1);
            money = money.substr(0,money.length-1);
            if (this.idArr.length) {
               
                var id = this.idArr.join(',');

                //alert(ad_id);
                Model.review({
                    data: {
                        id: id,
                        type: type,
                        ad_id:ad_id,
                        price:money
                    },
                    success: function(map) {
                        jAlert('操作成功！', function() {
                            _this.idArr = [];
                            alert('1') ;
                            _this.render();
                            location.reload()
                        });
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }
        },
        /*推荐/取消推荐*/
        recommend: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                Model.recommend({
                    data: {
                        id: id,
                        type: type
                    },
                    success: function(map) {
                        jAlert('操作成功！', function() {
                            _this.idArr = [];
                            _this.render();
                        });
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }
        },
        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.parents('tr').attr('data-id'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                jConfirm('确定要删除？', function(s) {
                    if (s) {
                        Model.delete({
                            data: {
                                id: id
                            },
                            success: function(map) {
                                jAlert('删除成功', function() {
                                    _this.idArr = [];
                                    _this.render();
                                })
                            }
                        })
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }

        }
    })
    return view;
})